package cn.kgc.oss.service.impl;

import cn.kgc.oss.service.OssService;
import cn.kgc.oss.utils.ConstantPropertiesUtils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;

/**
 * @ClassName OssServiceImpl
 * @Description: TODO
 * @Author :郭建宾
 * @Date 2020/7/3
 * @Version V1.0
 **/
@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = ConstantPropertiesUtils.END_POINT;
        // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        try {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 上传文件流。
        InputStream inputStream = file.getInputStream();

        //获取上传文件名称
        String fileName = file.getOriginalFilename();

        //生成UUID
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        fileName=uuid+fileName;

        //日期格式
        String dataPath = new DateTime().toString("yyyy/MM/dd");
        fileName = dataPath+"/"+fileName;

        ossClient.putObject(bucketName, fileName, inputStream);
        // 关闭OSSClient。
        ossClient.shutdown();

        // 拼接文件路径
        String url ="https://"+bucketName+"."+endpoint+"/"+fileName;
        return url;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }



    }
}
